/**
 * 项目辅助工具
 * 用于管理项目相关信息和跨项目集成
 */

const CACHE_KEY = {
  CURRENT_PROJECT: 'CURRENT_PROJECT'
};

// 默认项目
const DEFAULT_PROJECT = 'plm';

// 项目配置
const PROJECT_CONFIG = {
  oa: {
    id: 'oa',
    name: 'OA办公',
    icon: '/projects/oa/images/icon_project.png',
    color: '#0066cc',
    indexPage: 'projects/oa/pages/default/index/default_index'
  },
  plm: {
    id: 'plm',
    name: 'PLM研发',
    icon: '/projects/plm/images/icon_project.png',
    color: '#FF6600',
    indexPage: 'projects/plm/pages/default/index/default_index'
  },
  crm: {
    id: 'crm',
    name: 'CRM客户',
    icon: '/projects/crm/images/icon_project.png',
    color: '#00AA00',
    indexPage: 'projects/crm/pages/index/index'
  }
};

// 获取项目列表
function getProjectList() {
  return Object.values(PROJECT_CONFIG);
}

// 获取项目图标路径
function getProjectIcon(projectId) {
  if (!projectId) return '';
  const project = PROJECT_CONFIG[projectId];
  return project ? project.icon : '/images/icon_project.png';
}

// 获取项目名称
function getProjectName(projectId) {
  if (!projectId) return '';
  const project = PROJECT_CONFIG[projectId];
  return project ? project.name : '';
}

// 获取当前项目ID
function getCurrentProject() {
  try {
    const currentProject = wx.getStorageSync(CACHE_KEY.CURRENT_PROJECT);
    return currentProject || DEFAULT_PROJECT;
  } catch (error) {
    console.error('获取当前项目失败:', error);
    return DEFAULT_PROJECT;
  }
}

// 设置当前项目
function setCurrentProject(projectId) {
  try {
    wx.setStorageSync(CACHE_KEY.CURRENT_PROJECT, projectId);
    return true;
  } catch (error) {
    console.error('保存当前项目失败:', error);
    return false;
  }
}

// 项目路径前缀
function getProjectPathPrefix(projectId) {
  if (!projectId) projectId = getCurrentProject();
  return `/projects/${projectId}`;
}

// 获取项目资源路径
function getProjectResourcePath(projectId, path) {
  const prefix = getProjectPathPrefix(projectId);
  if (!path) return prefix;
  
  // 确保path以/开头
  if (path.charAt(0) !== '/') {
    path = '/' + path;
  }
  
  return prefix + path;
}

// 获取项目首页路径
function getProjectIndexPage(projectId) {
  if (!projectId) projectId = getCurrentProject();
  const project = PROJECT_CONFIG[projectId];
  return project ? project.indexPage : PROJECT_CONFIG[DEFAULT_PROJECT].indexPage;
}

module.exports = {
  getProjectList,
  getProjectIcon,
  getProjectName,
  getCurrentProject,
  setCurrentProject,
  getProjectPathPrefix,
  getProjectResourcePath,
  getProjectIndexPage,
  PROJECT_CONFIG
};
